<template>
  <el-container>
    <el-main class="main-wrapper">
      <div class="sticky-content-header">
        <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
          @select="handleSelect"
          router
          style="box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1)"
          background-color="#2E8B57"
          text-color="#ffffff"
          active-text-color="#E0FFFF"
        >
          <el-menu-item index="/office/first">首页</el-menu-item>
          <el-submenu index="/office/meeting">
            <template slot="title">个人中心</template>
                <el-menu-item :index="`/first/UserProfile/${queryParams.userId}/posts/posts`">我的帖子</el-menu-item>
                <el-menu-item :index="`/first/UserProfile/${queryParams.userId}/comments/comments`">我的评论</el-menu-item>
                <el-menu-item :index="`/first/UserProfile/${queryParams.userId}/following/following`">我的关注</el-menu-item>
                <el-menu-item :index="`/first/UserProfile/${queryParams.userId}/likes/likes`">我的收藏</el-menu-item>
          </el-submenu>
          <el-menu-item index="/office/first/PostForm" style="margin-left: auto;">发帖</el-menu-item>
        </el-menu>
        <div class="search-container">
          <form class="search-form" @submit.prevent>
            <input
              type="text"
              placeholder="请输入您要搜索的标题"
              v-model="queryParams.title"
              class="search-input"
              @keyup.enter="handleQuery"
            />
            <button
              type="submit"
              class="search-button"
              @click="handleQuery"
            ></button>
          </form>
        </div>
      </div>

      <div class="content-layout">
        <div class="sidebar-menu">
          <div
            class="category-items"
            :class="{ 'category-items-active': item.name === current }"
            v-for="item in categoryList"
            :key="item.categoryId"
            @click="selectCategory(item.name)"
          >
            {{ item.name }}
          </div>
        </div>

        <div class="post-list-container">
          <div class="post-item" v-for="item in postsList" :key="item.postId">
            <div class="post-content" @click="goDetail(item.postId)">
              <h3 class="post-title">{{ item.title }}</h3>
              <div class="post-excerpt" >{{extractTextAndTruncate(item.content)}}</div>
              <div class="post-meta">
                <span class="meta-item">
                  <i class="el-icon-user">{{ item.name }}</i>
                </span>
                <span class="meta-item">
                  <i class="el-icon-star-on">{{ item.likes }}</i>
                </span>
              </div>
            </div>
            <div
              class="post-image"
              v-if="item.imageUrl"
              @click="goDetail(item.postId)"
            >
              <img :src="item.imageUrl" alt="" />
            </div>
          </div>

          <div v-if="total === 0" class="no-data">暂无数据</div>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import { listPosts } from "@/api/forum/posts";
import { listCategory } from "@/api/forum/category";
import {getInfo} from "@/api/login";

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "first",
  created() {
    this.getList();
    this.load();
    this.getPersonId()
  },
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      queryParams: {
        pageNum: 1, // 当前页码
        pageSize: 10, // 每页显示条数
        title: null,
        userId: null,
        name: null,
        content: null,
        createdAt: null,
        likes: null,
        comments: null,
        status: null,
        updatedAt: null,
        imageUrl: null,
        viewCount: null,
        categoryName: null,
      },
      queryParamsCategory: {
        name: null,
        description: null,
      },
      total: 0, // 总数据量
      postsList: [], // 数据列表
      loading: false, //遮罩层
      categoryList: [], //分类列表
      current: "全部", //当前左栏的选中的分类
      // 上侧导航栏
      activeIndex: "1",
    };
  },

  methods: {
    // 帖子详情页
    goDetail(id) {
      if (!id) {
        console.error("帖子ID不能为空");
        this.$message.warning("帖子ID不能为空");
        return;
      }

      // 检查是否已经在详情页面，并且是同一个帖子
      if (this.$route.name === "detail" && this.$route.params.id == id) {
        console.log("已经在当前帖子详情页，无需重复跳转");
        return;
      }

      // 使用catch捕获重复导航错误
      this.$router
        .push({
          name: "detail",
          params: {id: id.toString()},
        })
        .then(() => {
          console.log("跳转成功!");
        })
        .catch((err) => {
          // 如果是重复导航错误，则忽略
          if (err.name === "NavigationDuplicated") {
            console.log("重复导航被忽略");
            return;
          }
          // 其他错误则抛出
          console.error("路由跳转错误:", err);
          this.$message.error(`跳转失败: ${err.message}`);
        });
    },

    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    //   左侧导航栏
    selectCategory(categoryName) {
      this.current = categoryName;
      // 如果分类名称是"全部"，则不传递分类参数
      if (categoryName === "全部") {
        this.queryParams.categoryName = null;
      } else {
        this.queryParams.categoryName = categoryName;
      }
      // 重新获取帖子列表
      this.getList();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    //   分类
    load() {
      listCategory(this.queryParamsCategory).then((response) => {
        this.categoryList = response.rows || [];
        this.categoryList.unshift({name: "全部"});
        this.loading = false;
      });
    },
    /** 查询帖子列表 */
    getList() {
      this.loading = true;
      listPosts(this.queryParams).then((response) => {
        this.postsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getPersonId() {
      getInfo().then(response => {
       this.queryParams.userId= response.user.userId;
      });
    },
  //   截取显示内容
    extractTextAndTruncate(html) {
      // 提取纯文本
      const div = document.createElement('div');
      div.innerHTML = html;
      // 返回纯文本内容，优先使用textContent，如果不存在则使用innerText
      let text = div.textContent || div.innerText || '';
      // 判断文本长度是否超过15，若超过则截取前15个字符并添加省略号
      return text.length > 15 ? text.slice(0, 30) + '......' : text;
    }
  },
};
</script>

<style>
:root {
  --primary-color: #2e8b57;
  --text-color: #333333;
  --border-radius: 8px;
}

.main-wrapper {
  background-color: #f0fff0;
  min-height: calc(100vh - 60px);
  padding: 0 12px;
  position: relative;
  overflow-y: auto;
}

.content-layout {
  display: flex;
  gap: 20px;
  max-width: 1200px;
  margin: 0 auto;
  position: relative;
}

.sidebar-menu {
  width: 180px;
  background: white;
  border-radius: var(--border-radius);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 10px;
  position: sticky;

  height: fit-content;
}

.post-list-container {
  flex: 1;
  background: white;
  border-radius: var(--border-radius);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  overflow-y: auto;
}

.category-items {
  padding: 12px 15px;
  font-size: 15px;
  cursor: pointer;
  border-radius: var(--border-radius);
  transition: all 0.3s ease;
  margin-bottom: 5px;
}

.category-items:hover {
  color: var(--secondary-color);
  transition: color 0.3s ease;
}

.category-items-active {
  background-color: var(--primary-color);
  color: white;
}

.post-list-container {
  flex: 1;
  background: white;
  border-radius: var(--border-radius);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.post-item {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #e8f5e9;
  transition: all 0.3s ease;
}

.post-item:hover {
  background-color: #f0fff0;
  transform: translateY(-2px);
}

.post-content {
  flex: 1;
  margin-right: 20px;
  cursor: pointer;
}

.post-title {
  font-size: 18px;
  color: var(--text-color);
  margin-bottom: 10px;
  font-weight: 600;
}

.post-excerpt {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.post-meta {
  display: flex;
  gap: 20px;
  color: #888;
  font-size: 13px;
}

.meta-item i {
  margin-right: 5px;
}

.post-image {
  width: 160px;
  height: 120px;
  border-radius: var(--border-radius);
  overflow: hidden;
}

.post-image {
  cursor: pointer;
}

.post-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.search-container {
  background: #f0fff0;
  padding: 20px 0;
}

.search-form {
  position: relative;
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
  display: flex;
}

.search-input {
  flex: 1;
  height: 46px;
  padding: 0 20px;
  font-size: 15px;
  border: 2px solid var(--primary-color);
  border-radius: var(--border-radius) 0 0 var(--border-radius);
  background: white;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.search-button {
  position: static;
  height: 46px;
  width: 80px;
  background: var(--primary-color);
  border: 2px solid var(--primary-color);
  border-radius: 0 var(--border-radius) var(--border-radius) 0;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.search-button:hover {
  background: #3cb371;
}

.search-button:before {
  content: "搜索";
  font-size: 15px;
}

.no-data {
  text-align: center;
  padding: 40px 0;
  color: #888;
  font-size: 15px;
}
/* 固定导航栏 */
.navbar{
  position: fixed;
  z-index: 1000; /* 确保导航栏在其他内容之上 */
  width: 75%;
}
.container {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: 900px;
  overflow-y: auto;  /*滚动条*/
}

.sticky-content-header {
  position: sticky;
  top: 0px;
  z-index: 1000;
  background: #f0fff0;
  margin: 0 -12px;
  padding: 0 12px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .content-layout {
    flex-direction: column;
  }

  .sidebar-menu {
    width: 100%;
    margin-bottom: 20px;
  }

  .search-form {
    width: 90%;
  }

  .post-item {
    flex-direction: column;
  }

  .post-image {
    width: 100%;
    height: 200px;
    margin-top: 15px;
  }

}
</style>

